<?php

namespace App\Service\Third;

use App\Constants\ErrorCode;
use App\Helpers\PayUtil;
use App\Helpers\NewPayUtil;
use App\Helpers\RedisUtil;
use App\Model\PaycallbackLog;
use App\Model\PayOrder;
use App\Model\Service\PaycallbackService;

/**
 * 新支付回调
 */
class NewPayCallbackService extends PayBaseService
{
    public function handle()
    {
	$callbackArray = $this->request->all();       
	//return $this->setError(ErrorCode::APPLE_PAY_VERIFY_ERR, $callbackArray);

	//先验证sign是否正确,不正确不改变状态值
	$sign = self::getSign($callbackArray);
	if ($sign != $callbackArray['sign']) {
	   log_info(__CLASS__ . "==SIGNERR==" . $sign. '!=' . $callbackArray['sign']); 
	   return ['result' => 0];
	}

	log_info(__CLASS__ . "==" . json_encode($callbackArray));
        //订单号
        $outTradeNo = $callbackArray['out_trade_no'];
	//return $this->setError(ErrorCode::APPLE_PAY_VERIFY_ERR, $outTradeNo);

	//回调如果支付不成功不改变状态值
	if ($callbackArray['trade_status'] != 'TRADE_SUCCESS') {
	    log_info(__CLASS__ . "==STATUSERR==" . $callbackArray['trade_status']);   
            return ['result' => 0];
	}
        //记录回调日志
        $record = PayOrder::getByOutTradeNo($outTradeNo);
	//return $this->setError(ErrorCode::APPLE_PAY_VERIFY_ERR, $record);       
	if (!$record) return ['result' => 0];
        PaycallbackLog::addRecord($record['channel'], $outTradeNo, $callbackArray);
	//return $this->setError(ErrorCode::APPLE_PAY_VERIFY_ERR, $a);  

        //处理订单
	$payMoney = $this->parsePayMoney($callbackArray);
//	return $this->setError(ErrorCode::APPLE_PAY_VERIFY_ERR, [$outTradeNo, $payMoney, $record['channel']]);
        $str = PaycallbackService::successCallback($outTradeNo, $payMoney, $record['channel']);
	//return $this->setError(ErrorCode::APPLE_PAY_VERIFY_ERR, $str);
	log_info(__CLASS__ . "==Success=={$outTradeNo}");
 	return ['result' => 1]; 
    }

    /**
     * 解析支付总金额（分）
     */
    protected function parsePayMoney($callbackArray = [])
    {
        return isset($callbackArray['money']) ? intval($callbackArray['money'] * 100) : 0;
    }

     // 计算签名
    protected function getSign($param){
        ksort($param);
        reset($param);
        $signstr = '';

        foreach($param as $k => $v){
            if($k != "sign" && $k != "sign_type" && $v!=''){
                $signstr .= $k.'='.$v.'&';
            }
        }
        $signstr = substr($signstr,0,-1);
        $signstr .= NewPayUtil::PAY_KEY;
        $sign = md5($signstr);
        return $sign;
    }
}

